package com.dxy.data.webcloud.up2u.controller;

import com.alibaba.fastjson.JSON;
import com.dxy.data.webcloud.up2u.Service.RoleService;
import com.dxy.data.webcloud.up2u.Service.UserService;
import com.dxy.data.webcloud.up2u.constants.PlatformConstant;
import com.dxy.data.webcloud.up2u.domain.OpenApiUserInfo;
import com.dxy.data.webcloud.up2u.domain.RoleDO;
import com.dxy.data.webcloud.up2u.domain.UserDO;
import com.dxy.data.webcloud.up2u.utils.ResponseDataHolder;
import com.dxy.platform.consts.Errors;
import com.dxy.platform.sdk.PlatformReturn;
import com.dxy.platform.sdk.old.*;
import com.dxy.platform.sdk.old.backstage.BackStageException;
import com.dxy.platform.sdk.old.backstage.TicketVerifyRequest;
import com.dxy.platform.utils.CollectionUtil;
import com.dxy.platform.utils.NumberUtil;
import com.dxy.platform.utils.TimeUtil;
import com.dxy.platform.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @CLassName: Up2uController
 * @Author: weixin
 * @Description: 用于up2u对接
 * @DATE: 2018/10/9 下午5:12
 * @Version: 1.0
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class Up2uController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    String projectName = "medicalbrain";

    private static final String MDM = "medicalbrain";

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Value("${server.port}")
    private int port;
    /**
     * 通过统一管理平台登录
     * @param httpServletRequest
     * @param httpServletResponse
     * @param ticket
     * @return
     */
    @GetMapping("/up2u/login")
    public ResponseDataHolder loginByUp2u(HttpServletRequest httpServletRequest,
                                          HttpServletResponse httpServletResponse,
                                          @RequestParam(value = "ticket", defaultValue = "") String ticket) {
        if (StringUtils.isBlank(ticket)) {
            logger.error("error up2u ticket black");
            return ResponseDataHolder.failure(Errors.TICKET_EXPIRED);
        }
//        TicketVerifyRequest request = new TicketVerifyRequest
//                (ticket, Projects.UMCC.NAME, WebUtil.getRemoteAddress(httpServletRequest), WebUtil.getUserAgent(httpServletRequest));
        TicketVerifyRequest request = new TicketVerifyRequest
                (ticket, PlatformConstant.PROJECT_NAME, WebUtil.getRemoteAddress(httpServletRequest), WebUtil.getUserAgent(httpServletRequest));

//        BackstageSdk sdk = BackstageSdk.of(Projects.UMCC.NAME);
        BackstageSdk sdk = BackstageSdk.of(PlatformConstant.PROJECT_NAME);
        String result;
        try {
            result = sdk.ticketVerify(request);
        } catch (BackStageException e) {
            e.printStackTrace();
            logger.error("error when validate up2u ticket");
            return ResponseDataHolder.failure("ticket错误！");
        }
        if (StringUtils.equals("wrong ticket", result)) {
            logger.error("error validate up2u wrong ticket");
            return ResponseDataHolder.failure(Errors.TICKET_EXPIRED);
        }
        UserDO userDO = userService.getByEmail(result);
        if (userDO != null) {
            try {
                httpServletResponse.sendRedirect("/index");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ResponseDataHolder.success();
        }
        logger.error("error build up2u user session " + result);
        return ResponseDataHolder.failure("未知用户！");
    }

    /**
     * @Author weixin
     * @Description 用于新增用户
     * @Date 下午4:43 2018/10/9
     * @Param [request]
     * @return com.dxy.platform.sdk.PlatformReturn
     **/
    @PostMapping(value = "/up2u/user/new")
    public PlatformReturn newUser(HttpServletRequest request) {

        System.out.println("响应来自端口：" + port);

        int timestamp = WebUtil.getAsInt(request, Consts.TIMESTAMP);
        if (timestamp < TimeUtil.toSeconds() - 1800) {
            return PlatformReturn.failure(3, Errors.EXPIRED_REQUEST);
        }

        PlatformSdk medicalBrain = PlatformSdk.of(PlatformConstant.PROJECT_NAME);
        String appId = medicalBrain.getProperty(PlatformConstant.OA_CERTIFICATE_APP_ID);
        String appSignKey = medicalBrain.getProperty(PlatformConstant.OA_CERTIFICATE_APP_SIGN_KEY);
        logger.info("appid: {} ", appId);
        logger.info("appSignKey: {} ", appSignKey);
        ApiSign apiSign = ApiSign.of(appId, appSignKey);
        String sign = WebUtil.getRawString(request, Consts.SIGN);
        String nonce = WebUtil.getRawString(request, Consts.NONCE);
        String roleId = WebUtil.getRawString(request, "role_id");
        String email = WebUtil.getRawString(request, "email");
        String name = WebUtil.getRawString(request, "name");
        String dxyname = WebUtil.getRawString(request, "dxyname");
        apiSign.add(Consts.NONCE, nonce);
        apiSign.add("role_id", roleId);
        apiSign.add("email", email);
        apiSign.add("name", name);
        apiSign.add("dxyname", dxyname);
        apiSign.add(Consts.TIMESTAMP, String.valueOf(timestamp));
        logger.info("timestamp: {} ", timestamp);
        logger.info("sign: {} ", sign);
        logger.info("nonce: {} ", nonce);
        logger.info("roleId: {} ", roleId);
        logger.info("email: {} ", email);
        logger.info("name: {} ", name);
        logger.info("dxyname: {} ", dxyname);
        String apiSignStr = apiSign.sign();
        logger.info("apiSign: {}", apiSignStr);
        if (!apiSignStr.equals(sign)) {
            return PlatformReturn.failure(3, Errors.INVALID_SIGN);
        }

        if (userService.getByEmail(email) != null) {
            return PlatformReturn.failure(1001, "email 无效");
        }
        if (userService.getByUsername(dxyname) != null) {
            return PlatformReturn.failure(1004, "dxyname 无效");
        }
        String[] roleIdStrArray = roleId.split(",");
        List<Integer> roleList = new ArrayList<>();
        for (String id : roleIdStrArray) {
            int realId = NumberUtil.parseIntQuietly(id);
            RoleDO roleDO = roleService.get(realId);
            if (roleDO == null) {
                return PlatformReturn.failure(1002, "角色 ID 无效");
            }
            roleList.add(realId);
        }
        UserDO userDO = new UserDO();
        userDO.setEmail(email);
        userDO.setName(name);
        userDO.setUsername(dxyname);
        userDO.setRoleIds(roleList);
        if (userService.save(userDO) > 0) {
            return PlatformReturn.success();
        }
        return PlatformReturn.failure(4001, "创建用户失败");
    }

    /**
     * @Author weixin
     * @Description 用于初始化用户数据的接口
     * @Date 下午4:53 2018/10/9
     * @Param [request]
     * @return com.dxy.platform.sdk.PlatformReturn
     **/
    @GetMapping("/up2u/user/info")
    public PlatformReturn findAllUserInfo(HttpServletRequest request) {
        PlatformSdk medicalbrain = PlatformSdk.of(PlatformConstant.PROJECT_NAME);
        String appId = medicalbrain.getProperty(PlatformConstant.UP2U_APP_ID);
        ApiApp apiApp = medicalbrain.getApiApp(NumberUtil.parseIntQuietly(appId));
        if (apiApp == null) {
            return PlatformReturn.failure(Errors.API_APP_NOT_FOUND);
        }
        int timestamp = WebUtil.getAsInt(request, Consts.TIMESTAMP);
        if (timestamp < TimeUtil.toSeconds() - 1800) {
            return PlatformReturn.failure(Errors.EXPIRED_REQUEST);
        }
        ApiSign apiSign = ApiSign.of(appId, apiApp.getAppSignKey());
        String sign = WebUtil.getRawString(request, Consts.SIGN);
        String nonce = WebUtil.getRawString(request, Consts.NONCE);
        apiSign.add(Consts.NONCE, nonce);
        apiSign.add(Consts.TIMESTAMP, String.valueOf(timestamp));
        if (!apiSign.sign().equals(sign)) {
            return PlatformReturn.failure(Errors.INVALID_SIGN);
        }
        List<UserDO> userInfoList = userService.list(new HashMap<>());
        List<OpenApiUserInfo> apiUserInfoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userInfoList)) {
            convertToOpenApiUserInfo(apiUserInfoList, userInfoList);
        }
        Map<String, Object> map = new HashMap<>();
        map.put(Consts.ITEMS, apiUserInfoList);
        PlatformReturn platformReturn = PlatformReturn.success();
        platformReturn.setResults(map);
        return platformReturn;
    }

    private void convertToOpenApiUserInfo(List<OpenApiUserInfo> apiUserInfoList, List<UserDO> userInfoList) {
        if (CollectionUtil.isNotEmpty(userInfoList)) {
            for (UserDO userInfo : userInfoList) {
                apiUserInfoList.add(new OpenApiUserInfo(userInfo));
            }
        }
    }

    @GetMapping("/up2u/test")
    public String test() {

        return "test";
    }
}
